package name.flurl.android.tt_news4android;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.widget.ArrayAdapter;

abstract class BaseNewsParser extends AsyncTask<Integer, Integer, NewsEntry[]> {
	protected URL mUrl = null;
	private ArrayAdapter<NewsEntry> mAdapter = null;

	public BaseNewsParser(ArrayAdapter<NewsEntry> adapter) {
		this.mAdapter = adapter;
	}

	protected static InputStream getData(String url) throws Exception {
		// Log.i("POGA Events", "fetching events from "+url);
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(new URI(url));

		HttpResponse response = client.execute(request);
		return response.getEntity().getContent();
	}

	@Override
	protected void onPostExecute(NewsEntry[] events) {
		NewsAdapter adapter = (NewsAdapter) mAdapter;
		adapter.addEvents(events);
	}

	protected URL getUrl() {
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(mAdapter.getContext()
						.getApplicationContext());
		if (sp.getBoolean("useUUIDPref", false))
			try {
				return new URL(mUrl.toString() + "&UUID="
						+ sp.getString("UUIDPref", ""));
			} catch (MalformedURLException e) {
				e.printStackTrace();
				return null;
			}
		return mUrl;
	}
}
